package com.lyd.seckill.serviceimpl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyd.seckill.mapper.SeckillOrderMapper;
import com.lyd.seckill.pojo.SeckillOrder;
import com.lyd.seckill.pojo.User;
import com.lyd.seckill.service.ISeckillOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 */
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService {


    @Autowired
    private SeckillOrderMapper seckillOrderMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 获取秒杀结果
     * @param user
     * @param goodsId
     * @return orderId:成功，  -1:秒杀失败，  0：排队中
     */
    @Override
    public Long getResult(User user, Long goodsId) {
        QueryWrapper<SeckillOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("user_id",user.getId()).eq("goods_id",goodsId);
        SeckillOrder seckillOrder = seckillOrderMapper.selectOne(orderQueryWrapper);

        if (seckillOrder!=null){
            return seckillOrder.getOrderId();
        }else if (redisTemplate.hasKey("isStockEmpty:" + goodsId)){
            return -1L;

        }else {
            return 0L;
        }

    }
}
